package com.desay.pangoo.itmt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.desay.pangoo.common.lite.lang.web.BusinessException;
import com.desay.pangoo.common.lite.lang.web.CommonResponse;
import com.desay.pangoo.itmt.controller.vo.OrgChartVo;
import com.desay.pangoo.itmt.entity.OrgChartEntity;
import com.desay.pangoo.itmt.enums.ExceptionCodeEnum;
import com.desay.pangoo.itmt.repository.OrgChartRepository;
import com.desay.pangoo.itmt.repository.spec.ExpandCriteria;
import com.desay.pangoo.itmt.service.OrgChartService;
import com.desay.pangoo.itmt.utils.ExportUtil;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;

/**
 * 数据集
 *
 * @author uidq1163
 */
@RestController
@Api(tags = "ITMT组织架构")
@RequestMapping(value = "/orgChart")
@Validated
@Slf4j
public class OrgChartController {
	@Autowired
	private OrgChartService orgChartService;
	@Autowired
	private OrgChartRepository orgChartRepository;

	@PostMapping
	@ApiOperation(value = "添加组织架构人员信息", notes = "添加组织架构人员信息")
	public ResponseEntity<Object> create(@RequestBody OrgChartVo vo) {
		Long id = orgChartService.create(vo);
		return new ResponseEntity<>(CommonResponse.success(id), HttpStatus.OK);
	}

	@DeleteMapping(value = "{id}")
	@ApiOperation(value = "删除", notes = "删除组织架构人员信息")
	@ApiImplicitParam(name = "id", value = "组织架构人员信息ID", required = true, dataTypeClass = Long.class, paramType = "path")
	public ResponseEntity<Object> delete(@PathVariable long id) {
		try {
			orgChartService.delete(id);
		} catch (DataIntegrityViolationException e) {
			throw new BusinessException(ExceptionCodeEnum.ORG_CHART_HAS_CHILDREN);
		}
		return new ResponseEntity<>(CommonResponse.success(), HttpStatus.OK);
	}

	@PutMapping(value = "{id}")
	@ApiOperation(value = "更新", notes = "更新组织架构人员信息")
	public ResponseEntity<Object> update(@PathVariable(value = "id") Long id, @RequestBody OrgChartVo vo) {
		orgChartService.update(id, vo);
		return new ResponseEntity<>(CommonResponse.success(), HttpStatus.OK);
	}

	@GetMapping(value = "")
	@ApiOperation(value = "获取组织架构", notes = "获取组织架构")
	public ResponseEntity<Object> getAllList() {
		return new ResponseEntity<>(CommonResponse.success(orgChartService.getOrgChart()), HttpStatus.OK);
	}

	@GetMapping(value = "{id}")
	@ApiOperation(value = "获取工作组内所有成员", notes = "获取工作组内所有成员")
	public ResponseEntity<Object> getAllListByWorkGroup(@PathVariable(value = "id") Long id) {
		return new ResponseEntity<>(CommonResponse.success(orgChartService.getOrgChartByWorkGroupId(id)),
				HttpStatus.OK);
	}

	@GetMapping(value = "/avatar")
	@ApiOperation(value = "获取用户头像信息")
	public void getUserAvatar(@RequestParam(value = "path") String filePath, HttpServletResponse resp) {

		File file = new File(filePath);
		if (!file.exists()) {
			throw new BusinessException(ExceptionCodeEnum.ORG_CHART_USER_AVATAR_NOT_EXIST);
		}
		resp.setContentType("application/octet-stream");
		try {
			resp.setHeader("Content-Disposition",
					String.format("attachment; filename=\"%s\"", URLEncoder.encode(FileUtil.getName(file), "UTF-8")));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
		resp.setHeader("Pragma", "no-cache");
		resp.setHeader("Expires", "0");
		try (InputStream in = new FileInputStream(file);) {
			resp.setHeader(HttpHeaders.CONTENT_LENGTH, file.length() + "");
			IOUtils.copyLarge(in, resp.getOutputStream());
			resp.flushBuffer();
			resp.getOutputStream().close();
		} catch (Exception e) {
			log.error("{}", e);
		}
	}

	@GetMapping(value = "org/{orgRole}")
	@ApiOperation(value = "根据角色获取所有成员", notes = "根据角色获取所有成员（组织角色:ITMT ChairMan:1，ITMT Leader:2，ITMT SubLeader:3，ITMT成员:4，TSP:5）")
	public ResponseEntity<Object> getOrgInfo(@PathVariable(value = "orgRole") Integer orgRole) {
		return new ResponseEntity<>(CommonResponse.success(orgChartService.getOrgInfo(orgRole)), HttpStatus.OK);
	}

	@GetMapping(value = "org/{orgRole}/info")
	@ApiOperation(value = "根据角色获取所有成员", notes = "根据角色获取所有成员（组织角色:ITMT ChairMan:1，ITMT Leader:2，ITMT SubLeader:3，ITMT成员:4，TSP:5）")
	public ResponseEntity<Object> getOrgInfoByOrgRole(@PathVariable(value = "orgRole") Integer orgRole) {
		return new ResponseEntity<>(CommonResponse.success(orgChartService.getOrgInfoByOrgRole(orgRole)),
				HttpStatus.OK);
	}

	@GetMapping(value = "org/check")
	@ApiOperation(value = "判断当前用户角色是否存在", notes = "判断当前用户角色是否存在（组织角色:ITMT ChairMan:1，ITMT Leader:2，ITMT SubLeader:3，ITMT成员:4，TSP:5）")
	public ResponseEntity<Object> getUserWorkGroup(@RequestParam(value = "orgRole") Integer orgRole,
			@RequestParam(value = "login") String login) {
		return new ResponseEntity<>(CommonResponse.success(orgChartService.getUserWorkGroup(orgRole, login)),
				HttpStatus.OK);
	}

	@GetMapping(value = "org/{workGroupId}/{orgRole}")
	@ApiOperation(value = "根据工作组及类型获取成员", notes = "根据工作组角色获取所有成员（组织角色:ITMT ChairMan:1，ITMT Leader:2，ITMT SubLeader:3，ITMT成员:4，TSP:5）")
	public ResponseEntity<Object> getOrgInfoByWorkGroup(@PathVariable(value = "orgRole") Integer orgRole,
			@PathVariable(value = "workGroupId") Long workGroupId) {
		return new ResponseEntity<>(CommonResponse.success(orgChartService.getUserByWorkGroup(orgRole, workGroupId)),
				HttpStatus.OK);
	}

	@GetMapping(value = "org/workgroup")
	@ApiOperation(value = "获取leader所在的域")
	public ResponseEntity<Object> getUserWorkGroup() {
		return new ResponseEntity<>(CommonResponse.success(orgChartService.getUserWorkGroup()), HttpStatus.OK);
	}

	@GetMapping(value = "org/download", headers = "Accept=application/octet-stream")
	@ApiOperation(value = "下载组织架构信息")
	public void download(HttpServletResponse response) throws IOException {
		ExpandCriteria<OrgChartEntity> c = new ExpandCriteria<>();
		ExportUtil<OrgChartEntity> exportUtil = new ExportUtil<>(orgChartRepository, c);
		exportUtil.export("ITMT列表", response, this::process);
	}

	/**
	 * 指定表头信息和内容
	 *
	 * @param objMap
	 * @return
	 */
	private Map<String, Object> process(OrgChartEntity objMap) {
		Map<String, Object> row = new LinkedHashMap<>();
		row.put("uid", objMap.getLogin());
		row.put("全称", objMap.getNickName());
		row.put("邮件", objMap.getEmail());
		row.put("所属域", objMap.getWorkGroup() != null ? objMap.getWorkGroup().getWorkGroupName() : "");
		switch (objMap.getOrgRole()) {
		// ITMT ChairMan:1，ITMT Leader:2，ITMT SubLeader:3，ITMT成员:4,TSP:5,PRG:6
		case 1:
			row.put("角色类型", "ChairMan");
			break;
		case 2:
			row.put("角色类型", "ITMT Leader");
			break;
		case 3:
			row.put("角色类型", "ITMT SubLeader");
			break;
		case 4:
			row.put("角色类型", "TMT成员");
			break;
		case 5:
			row.put("角色类型", "TSP");
			break;
		case 6:
			row.put("角色类型", "PRG");
			break;
		default:
			row.put("角色类型", "");
			break;
		}
		return row;
	}
}
